package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"

	cherryeditor "adm1/components/cherry_editor"
	"adm1/models"
	"adm1/pages"
	"adm1/plugins/filemanager"
	"adm1/plugins/filemanager/modules/root"
	"adm1/plugins/librarian"
	"adm1/tables"

	"github.com/GoAdminGroup/components/echarts"
	ada "github.com/GoAdminGroup/go-admin/adapter/gin" // web framework adapter
	adminContext "github.com/GoAdminGroup/go-admin/context"
	"github.com/GoAdminGroup/go-admin/engine"
	"github.com/GoAdminGroup/go-admin/modules/auth"
	_ "github.com/GoAdminGroup/go-admin/modules/db/drivers/sqlite" // sql driver
	amodels "github.com/GoAdminGroup/go-admin/plugins/admin/models"
	"github.com/GoAdminGroup/go-admin/template"
	"github.com/GoAdminGroup/go-admin/template/chartjs"
	_ "github.com/GoAdminGroup/themes/adminlte"
	_ "github.com/GoAdminGroup/themes/sword" // ui theme
	"github.com/gin-gonic/gin"
	_ "modernc.org/sqlite"
)

// 加载配置文件
var config, site = loadInstallConfig()

var R = gin.Default()
var Eng = engine.Default()

func main() {
	startServer()
}
func startServer() {

	gin.SetMode(gin.ReleaseMode)
	gin.DefaultWriter = io.Discard

	template.AddComp(chartjs.NewChart())
	template.AddComp(echarts.NewChart())
	template.AddComp(cherryeditor.New())
	// template.AddComp(wangeditor.New())
	dir, _ := os.Getwd()
	const visitorRoleID = int64(3)
	if err := Eng.AddConfigFromYAML("./config.yml").
		AddGenerators(tables.Generators).
		AddPlugins(librarian.NewLibrarianWithConfig(librarian.Config{
			Path:           "./plugins/docs",
			MenuUserRoleID: visitorRoleID,
			BuildMenu:      true,
			Prefix:         "librarian",
		}),
			filemanager.NewFileManager(filepath.Join(dir, "plugins/docs")).
				AddRoot("code", root.Root{Path: filepath.Join(dir, "plugins/code"), Title: "Code"}).
				AddRoot("picture", root.Root{Path: filepath.Join(dir, "./html/images"),
					Title: "Picture"})).
		// AddPlugins(filemanager.NewFileManagerWithConfig(filemanager.Config{
		// 	Path:          "./plugins/fm_example",
		// 	AllowDelete:   false,
		// 	AllowUpload:   true,
		// 	AllowDownload: true,
		// 	AllowRename:   true,
		// 	AllowMove:     true,
		// })).
		// AddPlugins(librarian.NewLibrarianWithConfig(librarian.Config{
		// 	Path:      "./plugins/fm_example/docs",
		// 	BuildMenu: true,
		// 	Prefix:    "librarian",
		// })).
		ResolveSqliteConnection(tables.SetConn).
		Use(R); err != nil {
		panic(err)
	}

	R.Static("/uploads", "./uploads")
	R.Static("/game", "./game")
	R.Static("/assets", "./html")
	R.Static("/wang", "./html/wang")
	R.Static("/js", "./"+themeDir+"default/js")
	R.Static("/css", "./"+themeDir+"default/css")
	R.Static("/admin/assets/fonts", "./components/cherry_editor/assets/fonts")
	// R.Static("/wangeditor", "./"+templateDir+"admin/js/wangeditor")
	R.Static("/public", "./"+datadir+"public")

	Eng.Data("GET", "/admin/librarian", func(ctx *adminContext.Context) {
		conn := Eng.SqliteConnection()
		user := amodels.User().SetConn(conn).Find(visitorRoleID)
		_ = auth.SetCookie(ctx, user, conn)
		ctx.Redirect("/admin/librarian/README")
	}, true)

	Eng.Data("GET", "/admin/example", func(ctx *adminContext.Context) {
		ctx.Redirect("/admin/plugins/fm_example/docs/README.md")
	}, true)

	Eng.HTML("GET", "/admin", pages.GetDashBoard)
	Eng.HTMLFile("GET", "/admin/hello", "./html/hello.tmpl", gin.H{
		"msg": "Hello world",
	})
	Eng.HTMLFile("GET", "/wang", "./html/wang-editor.html", gin.H{
		"msg": "Hello world",
	})
	Eng.HTMLFile("GET", "/cherry", "./html/cherry.html", gin.H{
		"msg": "Hello world",
	})

	R.LoadHTMLGlob("html/*.html")
	// R.LoadHTMLGlob("theme/default/*.html")
	// dir, _ := os.Getwd()
	// index:=filepath.Join(dir, "game/game_falling_ball.html")
	// println(index)

	// r.GET("/", func(ctx *gin.Context) {
	// 	ctx.HTML(http.StatusOK, "theme/default/index.html", gin.H{"basePath": "theme/default/"})
	// })

	models.Init(Eng.SqliteConnection())

	//加载页面模板
	err := loadTemplate()
	if err != nil { // 初始化模板异常
		panic(funcT("Template initialization anomaly"))
	}
	//初始化导航菜单路由
	initCategoryRoute()

	admin := R.Group("/admin")
	admin.GET("/echarts", ada.Content(pages.GetDashBoard3Content))
	admin.GET("/table", ada.Content(pages.GetTableContent))
	admin.GET("/form1", ada.Content(pages.GetForm1Content))

	// r.GET("/admin/echarts", ada.Content(pages.GetDashBoard3Content))
	// r.GET("/admin/table", ada.Content(pages.GetTableContent))
	// r.GET("/admin/form1", ada.Content(pages.GetForm1Content))

	Eng.Data("POST", "/admin/form/update", func(ctx *adminContext.Context) {
		fmt.Println("ctx.PostForm()", ctx.PostForm())
		ctx.PjaxUrl("/admin")
	})
	Eng.Data("POST", "/admin/popup/form", func(ctx *adminContext.Context) {
		ctx.JSON(http.StatusOK, map[string]interface{}{
			"code": 200,
			"msg":  "ok",
			"data": map[string]string{
				"url": "/admin/info/profile",
			},
		})
	})

	// http://doc.go-admin.cn/zh/admin/module/
	// conn := eng.SqliteConnection()
	// SetConn(conn)

	_ = R.Run(":8910")

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Print("closing database connection")
	Eng.SqliteConnection().Close()
}

// var globalConn db.Connection

// func SetConn(conn db.Connection) {
// 	globalConn = conn
// }
